package com.tonyodev.fetch2core;

import ohos.app.Context;
import ohos.net.NetCapabilities;
import ohos.net.NetManager;
import ohos.wifi.WifiDevice;

import org.jetbrains.annotations.NotNull;

/**
 * 网络工具类
 *
 * @since 2021-05-20
 */
public class FetchExtensions {
    /**
     * 是否开启wifi
     *
     * @param context 上下文
     * @return wifi是否开启
     */
    public static boolean isOnWiFi(@NotNull Context context) {
        NetManager netManager = NetManager.getInstance(context);
        if (netManager != null && netManager.hasDefaultNet()) {
            WifiDevice wifiDevice = WifiDevice.getInstance(context);
            return wifiDevice != null && wifiDevice.isWifiActive() && wifiDevice.isConnected();
        } else {
            return false;
        }
    }

    /**
     * 是否开启计量流量
     *
     * @param context 上下文
     * @return 是否开启
     */
    public static boolean isOnMeteredConnection(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        return netManager != null && netManager.isDefaultNetMetered();
    }

    /**
     * 网络是否可用
     *
     * @param context 上下文
     * @return 是否链接
     */
    public static boolean isNetworkAvailable(Context context) {
        NetManager netManager = NetManager.getInstance(context);
        boolean connected;
        if (netManager.hasDefaultNet() && netManager.getDefaultNet() != null) {
            NetCapabilities capabilities = netManager.getNetCapabilities(netManager.getDefaultNet());
            connected = capabilities.hasBearer(NetCapabilities.BEARER_WIFI) || capabilities.hasBearer(NetCapabilities.BEARER_CELLULAR);
        } else {
            connected = false;
        }
        return connected;
    }
}
